<?php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use common\components\Helper;
use backend\components\Icon;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'sysinfo', 'icon'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        Helper::addEntries([
            [
                'label' => Yii::t('site', 'SUBMENU_CONTENT')
            ],
            [
                'label' => Icon::i('fa-pencil') . Yii::t('site', 'SUBMENU_ADD_ARTICLE'),
                'url' => ['content/articles/create']
            ],
            [
                'label' => Icon::i('stack') . Yii::t('site', 'SUBMENU_ARTICLES'),
                'url' => ['/content/articles']
            ],
            [
                'label' => Icon::i('fa-folder-open') . Yii::t('site', 'SUBMENU_ARTICLES_CATEGORIES'),
                'url' => ['/categories/default', 'extension' => 'mod_content']
            ],
            [
                'label' => Icon::i('fa-picture-o') . Yii::t('site', 'SUBMENU_MEDIA'),
                'url' => ['/media/default']
            ],
            [
                'label' => '前台配置'
            ],
            [
                'label' => Icon::i('fa-list') . '菜单管理',
                'url' => ['/admin/menu-types']
            ],
            [
                'label' => Icon::i('fa-cube') . '小部件管理',
                'url' => ['/widgets']
            ],
            [
                'label' => '系统配置'
            ],
            [
                'label' => Icon::i('fa-cog') . '全局配置',
                'url' => ['/menus/index']
            ],
            [
                'label' => Icon::i('fa-eye') . '主题管理',
                'url' => ['/themes/styles']
            ],
            [
                'label' => Icon::i('fa-comment') . '语言管理',
                'url' => ['/languages/installed']
            ],
            [
                'label' => '扩展管理'
            ],
            [
                'label' => Icon::i('fa-download') . '安装扩展',
                'url' => ['/extensions/installer']
            ]
        ]);
        return $this->render('index');
    }

    public function actionSysinfo()
    {
        $db = Yii::$app->db;
        $formatter = Yii::$app->formatter;
        $data = [
            'info' => [
                'php' => php_uname(),
                'dbserver' => $db->driverName,
                'dbversion' => $db->serverVersion,
                'dbcharset' => $db->charset,
                'phpversion' => phpversion(),
                'server' => isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : getenv('SERVER_SOFTWARE'),
                'sapi_name' => php_sapi_name(),
                'version' => Yii::$app->version,
                'framework' => 'Yii ' . Yii::getVersion(),
                'useragent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''
            ],
            'phpSettings' => [
                'safe_mode' => Yii::t('common', ini_get('safe_mode') ? 'ON' : 'OFF'),
                'display_errors' => Yii::t('common', ini_get('display_errors') ?: 'NONE'),
                'short_open_tag' => Yii::t('common', ini_get('short_open_tag') == '1' ? 'ON' : 'OFF'),
                'file_uploads' => Yii::t('common', ini_get('file_uploads') == '1' ? 'ON' : 'OFF'),
                'magic_quotes_gpc' => Yii::t('common', ini_get('magic_quotes_gpc') ? 'ON' : 'OFF'),
                'register_globals' => Yii::t('common', ini_get('register_globals') ? 'ON' : 'OFF'),
                'output_buffering' => $formatter->asShortSize(ini_get('output_buffering')),
                'open_basedir' => Yii::t('common', ini_get('open_basedir') ?: 'NONE'),
                'session.save_path' => Yii::t('common', ini_get('session.save_path') ?: 'NONE'),
                'session.auto_start' => Yii::t('common', ini_get('session.auto_start') ? 'ON' : 'OFF'),
                'disable_functions' => ini_get('disable_functions'),
                'xml' => Yii::t('common', extension_loaded('xml') ? 'YES' : 'NO'),
                'zlib' => Yii::t('common', extension_loaded('zlib') ? 'YES' : 'NO'),
                'zip' => Yii::t('common', (function_exists('zip_open') && function_exists('zip_read')) ? 'YES' : 'NO'),
                'mbstring' => Yii::t('common', extension_loaded('mbstring') ? 'YES' : 'NO'),
                'iconv' => Yii::t('common', function_exists('iconv') ? 'YES' : 'NO'),
                'max_input_vars' => $formatter->asInteger(ini_get('max_input_vars'))
            ]
        ];

        ob_start();
        //date_default_timezone_set('UTC');
        phpinfo(INFO_GENERAL | INFO_CONFIGURATION | INFO_MODULES);
        $phpInfo = ob_get_contents();
        ob_end_clean();
        preg_match_all('#<body[^>]*>(.*)</body>#siU', $phpInfo, $output);
        $output = preg_replace('#<table[^>]*>#', '<table class="table table-striped adminlist">', $output[1][0]);
        $output = preg_replace('#(\w),(\w)#', '\1, \2', $output);
        $output = preg_replace('#<hr />#', '', $output);
        $output = str_replace('<div class="center">', '', $output);
        $output = preg_replace('#<tr class="h">(.*)<\/tr>#', '<thead><tr class="h">$1</tr></thead><tbody>', $output);
        $output = str_replace('</table>', '</tbody></table>', $output);
        $output = str_replace('</div>', '', $output);
        $data['phpInfo'] = $output;
        $msg = [
            'info' => Yii::t('site', 'SYSTEM_INFORMATION'),
            'phpSettings' => Yii::t('site', 'RELEVANT_PHP_SETTINGS'),
            'phpInfo' => Yii::t('site', 'PHP_INFORMATION'),
            'php' => Yii::t('site', 'PHP_BUILT_ON'),
            'dbserver' => Yii::t('site', 'DATABASE_TYPE'),
            'dbversion' => Yii::t('site', 'DATABASE_VERSION'),
            'dbcharset' => Yii::t('site', 'DATABASE_CHARSET'),
            'phpversion' => Yii::t('site', 'PHP_VERSION'),
            'server' => Yii::t('site', 'WEB_SERVER'),
            'sapi_name' => Yii::t('site', 'WEBSERVER_PHP_INTERFACE'),
            'version' => Yii::t('site', 'APPLICATION_VERSION'),
            'framework' => Yii::t('site', 'FRAMEWORK'),
            'useragent' => Yii::t('site', 'USER_AGENT'),
            'safe_mode' => Yii::t('site', 'SAFE_MODE'),
            'display_errors' => Yii::t('site', 'DISPLAY_ERRORS'),
            'short_open_tag' => Yii::t('site', 'SHORT_OPEN_TAGS'),
            'file_uploads' => Yii::t('site', 'FILE_UPLOADS'),
            'magic_quotes_gpc' => Yii::t('site', 'MAGIC_QUOTES'),
            'register_globals' => Yii::t('site', 'REGISTER_GLOBALS'),
            'output_buffering' => Yii::t('site', 'OUTPUT_BUFFERING'),
            'open_basedir' => Yii::t('site', 'OPEN_BASEDIR'),
            'session.save_path' => Yii::t('site', 'SESSION_SAVE_PATH'),
            'session.auto_start' => Yii::t('site', 'SESSION_AUTO_START'),
            'disable_functions' => Yii::t('site', 'DISABLED_FUNCTIONS'),
            'xml' => Yii::t('site', 'XML_ENABLED'),
            'zlib' => Yii::t('site', 'ZLIB_ENABLED'),
            'zip' => Yii::t('site', 'NATIVE_ZIP_ENABLED'),
            'mbstring' => Yii::t('site', 'MULTIBYTE_STRING_MBSTRING_ENABLED'),
            'iconv' => Yii::t('site', 'ICONV_AVAILABLE'),
            'max_input_vars' => Yii::t('site', 'MAXIMUM_INPUT_VARIABLES'),
        ];
        return $this->render('sysinfo', ['data' => $data, 'msg' => $msg]);
    }

    /**
     * Login action.
     * @return string
     * @throws yii\base\InvalidConfigException
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        $post = Yii::$app->request->post();

        if ($model->load($post) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->renderPartial('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * 显示字体图标
     * @return string
     */
    public function actionIcon()
    {
        $icon = require Yii::getAlias('@backend/config/icon.php');
        return $this->render('icon', ['icon' => $icon]);
    }
}
